import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { Level } from 'level';

interface Item {
  value: string;
}

@Injectable()
export class DbService implements OnModuleDestroy {
  private db = new Level('data/textMap', { valueEncoding: 'json' });
  private logger = new Logger(DbService.name);

  onModuleDestroy() {
    this.logger.debug('Close Database');
    return this.db.close();
  }

  async getText(hash: string): Promise<string | null> {
    const rst = await this.db.get<string, Item>(hash, {
      valueEncoding: 'json',
    });
    if (rst) {
      return rst.value;
    }

    return null;
  }

  async setText(key: string, value: string): Promise<boolean> {
    try {
      await this.db.put<string, Item>(
        key,
        {
          value,
        },
        {
          valueEncoding: 'json',
        },
      );
      return true;
    } catch (error) {
      this.logger.error(error);
      return false;
    }
  }

  async keys(limit = 10) {
    return await this.db.keys({ limit }).all();
  }
}
